home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 2790 < prev    next >
Encoding:
Text File  |  1996-08-06  |  2.2 KB  |  91 lines

  1. Path: atglab.bls.com!Alun.Champion
  2. From: Alun.Champion@bridge.bst.bls.com (Alun Champion)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: destructots and VC++
  5. Date: 19 Jan 1996 19:14:00 GMT
  6. Organization: Computer People Inc.
  7. Message-ID: <ALUN.CHAMPION.96Jan19141400@g7240065.bridge.bst.bls.com>
  8. References: <4doem9$7a8@zephyr.ens.tek.com>
  9. NNTP-Posting-Host: bstfirewall.bst.bls.com
  10. In-reply-to: Adam Smith's message of 19 Jan 1996 15:51:37 GMT
  11.  
  12. In article <4doem9$7a8@zephyr.ens.tek.com> Adam Smith <Adam_Smith@Lightworks-london.ccmail.compuserve.com> writes:
  13.  
  14. :  Has anyone noticed that the following does not work in VC++ 2.0.
  15.  
  16. :  Kipper* smoked = new Kipper();
  17. :  smoked->~Kipper();
  18.  
  19. :  This is just a noddy example, and is legal.
  20.  
  21. How do you mean "does not work" ?
  22.   It doesn't compile.
  23.   It doesn't have expected results.
  24.  
  25. Some compilers still require an explicit declaration of a destructor for
  26. this to compile. 
  27. The same as some compilers require an explicit declaration of operator= to
  28. be able to call
  29.  
  30.    a.operator=(b);
  31.  
  32. Which is a pain in the arse when trying to call a base class operator = when
  33. it doesn't have on defined
  34.  
  35. class A
  36. { };
  37.  
  38. class B : public A
  39. {
  40.   public:
  41.     const B& operator = (const B& b)
  42.     {
  43.         if (this == &b)
  44.             return *this;
  45.  
  46. // you have to use
  47.         *(A*)this = *(A*)&b;
  48. // instead of
  49. //      A::operator=(b);
  50.         return *this;
  51.     }
  52. };
  53.  
  54. Slowly but surely they are sorting these problems out.
  55.  
  56. Explicit calls to destructors can have all sorts of pit falls:
  57.  
  58.   calling a virtual destructor, when not meaning to.
  59.   calling a destructor on a stack object.
  60.   etc..
  61.  
  62. There is very little need to call destructors explicitly, one such case
  63. is in the operator = when defining the operator = in terms of the copy
  64. constructor and using new placement syntax
  65.  
  66. Example:
  67.  
  68.   #include <new.h>
  69.  
  70.   class A
  71.   {
  72.     public:
  73.       A(const A&);             // Complicated copy constructor.
  74.  
  75.       const A& operator = (const A& a)
  76.       {
  77.           if (this != &a) {
  78.               this->A::~A();   // Must ensure calling destructor for this class.
  79.               new (this) A(a);
  80.           }
  81.           return *this;
  82.       }
  83.       ...
  84.   };
  85.  
  86. Regards
  87.  
  88.   -A.
  89. -- 
  90. | A.Champion                |
  91.